"""
IP配置管理API
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.extensions import db
from app.models import IpConfig
from datetime import datetime
import ipaddress

ip_configs_bp = Blueprint('ip_configs', __name__, url_prefix='/api/ip-configs')


@ip_configs_bp.route('', methods=['GET'])
@jwt_required()
def get_ip_configs():
    """获取IP配置列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '')
        workshop = request.args.get('workshop', '')
        
        query = IpConfig.query
        
        # 搜索过滤
        if search:
            query = query.filter(
                (IpConfig.workshop.contains(search)) | 
                (IpConfig.line.contains(search)) |
                (IpConfig.ip.contains(search)) |
                (IpConfig.current_segment.contains(search))
            )
        
        # 车间过滤
        if workshop:
            query = query.filter(IpConfig.workshop == workshop)
        
        # 分页
        pagination = query.order_by(IpConfig.id).paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        ip_configs = [config.to_dict() for config in pagination.items]
        
        return jsonify({
            'ip_configs': ip_configs,
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page,
            'per_page': per_page
        }), 200
        
    except Exception as e:
        return jsonify({'message': f'获取IP配置列表失败: {str(e)}'}), 500


@ip_configs_bp.route('', methods=['POST'])
@jwt_required()
def create_ip_config():
    """创建IP配置"""
    try:
        data = request.get_json()
        workshop = data.get('workshop', '').strip()
        line = data.get('line', '').strip()
        ip = data.get('ip', '').strip()
        database_path = data.get('database_path', '').strip()
        segment_path = data.get('segment_path', '').strip()
        current_segment = data.get('current_segment', '').strip()
        is_enabled = data.get('is_enabled', True)
        
        # 验证必填字段
        if not workshop:
            return jsonify({'message': '车间不能为空'}), 400
        if not line:
            return jsonify({'message': '线别不能为空'}), 400
        if not ip:
            return jsonify({'message': 'IP地址不能为空'}), 400
        if not database_path:
            return jsonify({'message': '数据库路径不能为空'}), 400
        if not segment_path:
            return jsonify({'message': '分档路径不能为空'}), 400
        if not current_segment:
            return jsonify({'message': '在用分档不能为空'}), 400
        
        # 验证IP地址格式
        try:
            ipaddress.ip_address(ip)
        except ValueError:
            return jsonify({'message': 'IP地址格式不正确'}), 400
        
        # 检查IP是否已存在
        if IpConfig.query.filter_by(ip=ip).first():
            return jsonify({'message': 'IP地址已存在'}), 400
        
        # 创建IP配置
        ip_config = IpConfig(
            workshop=workshop,
            line=line,
            ip=ip,
            database_path=database_path,
            segment_path=segment_path,
            current_segment=current_segment,
            is_enabled=is_enabled
        )
        
        db.session.add(ip_config)
        db.session.commit()
        
        return jsonify({
            'message': 'IP配置创建成功',
            'ip_config': ip_config.to_dict()
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'创建IP配置失败: {str(e)}'}), 500


@ip_configs_bp.route('/<int:config_id>', methods=['PUT'])
@jwt_required()
def update_ip_config(config_id):
    """更新IP配置"""
    try:
        ip_config = IpConfig.query.get(config_id)
        if not ip_config:
            return jsonify({'message': 'IP配置不存在'}), 404
        
        data = request.get_json()
        
        # 更新车间
        if 'workshop' in data:
            workshop = data['workshop'].strip()
            if not workshop:
                return jsonify({'message': '车间不能为空'}), 400
            ip_config.workshop = workshop
        
        # 更新线别
        if 'line' in data:
            line = data['line'].strip()
            if not line:
                return jsonify({'message': '线别不能为空'}), 400
            ip_config.line = line
        
        # 更新IP地址
        if 'ip' in data:
            ip = data['ip'].strip()
            if not ip:
                return jsonify({'message': 'IP地址不能为空'}), 400
            
            # 验证IP地址格式
            try:
                ipaddress.ip_address(ip)
            except ValueError:
                return jsonify({'message': 'IP地址格式不正确'}), 400
            
            # 检查IP是否已被其他配置使用
            if ip != ip_config.ip:
                if IpConfig.query.filter_by(ip=ip).first():
                    return jsonify({'message': 'IP地址已存在'}), 400
                ip_config.ip = ip
        
        # 更新数据库路径
        if 'database_path' in data:
            database_path = data['database_path'].strip()
            if not database_path:
                return jsonify({'message': '数据库路径不能为空'}), 400
            ip_config.database_path = database_path
        
        # 更新分档路径
        if 'segment_path' in data:
            segment_path = data['segment_path'].strip()
            if not segment_path:
                return jsonify({'message': '分档路径不能为空'}), 400
            ip_config.segment_path = segment_path
        
        # 更新在用分档
        if 'current_segment' in data:
            current_segment = data['current_segment'].strip()
            if not current_segment:
                return jsonify({'message': '在用分档不能为空'}), 400
            ip_config.current_segment = current_segment
        
        # 更新启用状态
        if 'is_enabled' in data:
            ip_config.is_enabled = data['is_enabled']
        
        # 更新时间
        ip_config.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return jsonify({
            'message': 'IP配置更新成功',
            'ip_config': ip_config.to_dict()
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'更新IP配置失败: {str(e)}'}), 500


@ip_configs_bp.route('/<int:config_id>', methods=['DELETE'])
@jwt_required()
def delete_ip_config(config_id):
    """删除IP配置"""
    try:
        ip_config = IpConfig.query.get(config_id)
        if not ip_config:
            return jsonify({'message': 'IP配置不存在'}), 404
        
        db.session.delete(ip_config)
        db.session.commit()
        
        return jsonify({'message': 'IP配置删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'删除IP配置失败: {str(e)}'}), 500


@ip_configs_bp.route('/batch', methods=['DELETE'])
@jwt_required()
def batch_delete_ip_configs():
    """批量删除IP配置"""
    try:
        data = request.get_json()
        config_ids = data.get('ids', [])
        
        if not config_ids:
            return jsonify({'message': '请选择要删除的IP配置'}), 400
        
        # 查找所有要删除的配置
        ip_configs = IpConfig.query.filter(IpConfig.id.in_(config_ids)).all()
        
        if not ip_configs:
            return jsonify({'message': '未找到要删除的IP配置'}), 404
        
        # 删除配置
        for config in ip_configs:
            db.session.delete(config)
        
        db.session.commit()
        
        return jsonify({
            'message': f'成功删除 {len(ip_configs)} 个IP配置'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'message': f'批量删除IP配置失败: {str(e)}'}), 500


@ip_configs_bp.route('/<int:config_id>', methods=['GET'])
@jwt_required()
def get_ip_config(config_id):
    """获取单个IP配置详情"""
    try:
        ip_config = IpConfig.query.get(config_id)
        if not ip_config:
            return jsonify({'message': 'IP配置不存在'}), 404
        
        return jsonify({
            'ip_config': ip_config.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({'message': f'获取IP配置详情失败: {str(e)}'}), 500


@ip_configs_bp.route('/workshops', methods=['GET'])
@jwt_required()
def get_workshops():
    """获取所有车间列表"""
    try:
        workshops = db.session.query(IpConfig.workshop).distinct().all()
        workshop_list = [workshop[0] for workshop in workshops]
        
        return jsonify({
            'workshops': workshop_list
        }), 200
        
    except Exception as e:
        return jsonify({'message': f'获取车间列表失败: {str(e)}'}), 500